﻿using RabbitMQ.Client.Events;
using RabbitMQ.Client;
using System.Text;
using EntityModels.E01.Systems;
using System.Text.Json;
using ORM;
using Microsoft.AspNetCore.SignalR;
using WebAPI.Hubs;
using Commons.Enums;

namespace WebAPI.Consumers
{
    public class NotificationConsumer : BackgroundService
    {
        private readonly IConnection _connection;
        private readonly IModel _channel;
        private readonly IServiceProvider _serviceProvider;

        public NotificationConsumer(IConfiguration config, IServiceProvider serviceProvider)
        {
            var factory = new ConnectionFactory();
            factory.HostName = "127.0.0.1";
            factory.Port = 5672;//5672是RabbitMQ默认的端口号
            factory.UserName = "admin";
            factory.Password = "admin";
            factory.VirtualHost = "my_vhost";
            _connection = factory.CreateConnection();
            _channel = _connection.CreateModel();
            _channel.QueueDeclare(queue: "notifications_queue", durable: true, exclusive: false);
            _serviceProvider = serviceProvider;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var consumer = new EventingBasicConsumer(_channel);
            consumer.Received += async (model, ea) =>
            {
                var body = ea.Body.ToArray();
                var message = JsonSerializer.Deserialize<NotificationMessage>(Encoding.UTF8.GetString(body));
                var content = "";
                // 使用独立的作用域处理数据库操作
                using (var scope = _serviceProvider.CreateScope())
                {
                    var context = scope.ServiceProvider.GetRequiredService<PSPDbContext>();

                    // 生成通知内容（动态模板）
                    var sender = await context.Users.FindAsync(message.SenderId);
                    
                    switch (message.Type)
                    {
                        case NotificationTypeEnum.关注通知:
                            content = $"用户 {sender.NickName} 关注了你";
                            break;
                        case NotificationTypeEnum.点赞通知:
                            content = $"用户 {sender.NickName} 点赞了你作品{message.PhotographName}";
                            break;
                        case NotificationTypeEnum.收藏通知:
                            content = $"用户 {sender.NickName} 收藏了你作品{message.PhotographName}";
                            break;
                        case NotificationTypeEnum.违规通知:
                            content = $"你作品{message.PhotographName}出现违规，已被下架";
                            break;

                    }

                    // 插入通知记录
                    var notification = new Notification
                    {
                        RecipientId = message.ReceiverId,
                        SenderId = message.SenderId,
                        NotificationType = message.Type,
                        Content = content,
                        IsRead = false,
                        CreationTime = DateTime.Now
                    };
                    context.Notifications.Add(notification);
                    await context.SaveChangesAsync();

                    // 触发 SignalR 实时推送
                    var signalRHub = scope.ServiceProvider.GetRequiredService<IHubContext<NotificationHub>>();
                    await signalRHub.Clients.User(message.ReceiverId.ToString())
                        .SendAsync("ReceiveNotification", notification);
                }

                _channel.BasicAck(ea.DeliveryTag, false);
            };

            _channel.BasicConsume(queue: "notifications_queue", autoAck: false, consumer: consumer);
            return Task.CompletedTask;
        }
    }
}
